// 默认7天过期
const DEFAULT_CACHE_TIME: number = 60 * 60 * 24 * 7;
interface storageConfig {
  storage: any,
  prefixKey?: string
}
class Storage {
  prefixKey?: string;
  storage: any
  constructor(config: storageConfig) {
    this.prefixKey = config.prefixKey
    this.storage = config.storage
  }
  private getKey(key: string) {
    return `${this.prefixKey}_${key}`.toUpperCase();
  }

  //设置缓存
  set(key: string, value: any, expire: number | null = DEFAULT_CACHE_TIME): void {
    const stringData: string = JSON.stringify({
      value,
      expire: expire !== null ? new Date().getTime() + expire * 1000 : null
    });
    this.storage.setItem(this.getKey(key), stringData);
  }

  //获取缓存
  get<T = any>(key: string, def: any = null): T {
    const item = this.storage.getItem(this.getKey(key));
    if (item) {
      try {
        const data = JSON.parse(item);
        const { value, expire } = data;
        if (expire === null || expire >= Date.now()) {
          return value;
        } else {
          this.remove(key);
          return def;
        }
      } catch (e) {
        return def;
      }
    } else {
      return def;
    }
  }
  //删除缓存某一项
  remove(key: string): void {
    this.storage.removeItem(this.getKey(key));
  }
  // 清空所有
  clear(): void {
    this.storage.clear();
  }

  //cookie
  setCookie(name: string, value: any, expire: number | null = DEFAULT_CACHE_TIME): void {
    document.cookie = `${this.getKey(name)}=${value}; Max-Age=${expire}`;
  }
  getCookie(name: string): string {
    const cookieArr = document.cookie.split('; ');
    for (let i = 0, length = cookieArr.length; i < length; i++) {
      const kv = cookieArr[i].split('=');
      if (kv[0] === this.getKey(name)) {
        return kv[1];
      }
    }
    return '';
  }
  removeCookie(key: string): void {
    this.setCookie(key, 1, -1);
  }
  clearCookie(): void {
    const keys = document.cookie.match(/[^ =;]+(?==)/g);
    if (keys) {
      for (let i = keys.length; i--;) {
        document.cookie = `${keys[i]}=0;expire=${new Date(0).toUTCString()}`;
      }
    }
  }
};
function createStorage({ prefixKey = '', storage = localStorage }) {
  //本地缓存类
  return new Storage({ prefixKey, storage });
};

const storageUtil = createStorage({
  prefixKey: 'qc_web_base_version',
  storage: localStorage
});

export default storageUtil;
